import { computed } from "vue";
import { IMP3Data } from "./useRequest";

export interface ITree {
	label: string;
	children?: ITree[];
	id?: number;
	meta: {
		key?: string;
	};
}

export function checkTreeFirstNodeLabel(tree: ITree[], checkLabel: string) {
	return tree.map(({ label }) => label).includes(checkLabel);
}

export function matchTreeLabel(tree: ITree[], checkLabel: string) {
	return tree.filter(({ label }) => label === checkLabel)[0];
}

export function genTreesByArtist(mp3Data: IMP3Data[]) {
	let count = 1;
	const data: ITree[] = [];
	mp3Data
		.filter((item) => item.mediatype === "AUDIO")
		.forEach((item) => {
			const { album, title, artist, key } = item;

			if (!checkTreeFirstNodeLabel(data, artist)) {
				const node: ITree = {
					label: artist,
					children: [],
					id: count++,
					meta: {},
				};
				data.push(node);
			}

			const nodeAlbum = matchTreeLabel(data, artist);

			if (!nodeAlbum?.children) {
				nodeAlbum.children = [];
			}

			if (!checkTreeFirstNodeLabel(nodeAlbum.children, album)) {
				const node: ITree = {
					label: album,
					children: [],
					id: count++,
					meta: {},
				};
				nodeAlbum.children.push(node);
			}

			const nodeLast = matchTreeLabel(nodeAlbum.children, album);

			if (!nodeLast?.children) {
				nodeLast.children = [];
			}

			const music: ITree = { label: title, meta: { key }, id: count++ };

			nodeLast.children.push(music);
		});

	return { data, count };
}

export function compareTags(tags: string[], targetTags: string[], flag = true) {
	if (tags.length === 0) {
		return true;
	}
	if (flag) {
		for (const tag of tags) {
			if (targetTags.includes(tag)) {
				return true;
			}
		}
		return false;
	} else {
		for (const tag of tags) {
			if (!targetTags.includes(tag)) {
				return false;
			}
		}
		return true;
	}
}

export function getAllTags(data: IMP3Data[]) {
	const list: string[] = [];
	for (const { tags } of data) {
		for (const tag of tags) {
			if (!list.includes(tag)) {
				list.push(tag);
			}
		}
	}
	return list;
}
